﻿var RATE= Number($.cookie('GemRate'));
var app_url=location.origin;
(function () {
    var cart = {
        init: function () {
            var scrollToph;
            var num = 0;//选中的行数
            var rmb = 0;//每卡
            var total = 0;//总价
            this.loadCart();
            this.bindEvents();
        },
        bindEvents: function () {
            var self = this;
             //导航栏的选中
             $('.wrapper').navbarscroll();
            $("#categories li").eq(3).addClass("cur").siblings().removeClass("cur");
             //跳转页面
             $("#categories a").on("click",function(){
            	var link_url=$(this).attr("data-href");
            	if(APP){
            		var appJson={};
           			appJson.title=$(this).attr("data-title");
           			appJson.url=app_url+link_url;	
           			YiYi_APP.showNewPage(JSON.stringify(appJson));
            	}else{
            		location.href = link_url;
            	}
            });
            //点击关闭钻石详情
            $(".close-detail-btn").on("click", function (ev) {
                self.closeDatail($(this));
            });
            //移除购物车
            $(".remove-cart-btn").on("click", function (ev) {
            	var catrId = $("#cart .check_list_box span.selected").attr("lang");
            	if($("#cart .check_list_box span").is(".selected")){
            		myApp.confirm(_('确定移除购物车吗？'),'',function(){
            		 	self.removeCart(catrId);
            		});
            	}else{
            		myApp.alert(_("请选择!"));
            	}
            });
              //随便逛逛
           $("#go_shop").on("click",function(){
           		var link_url="/Customer/Gem?team=0";
           		if(APP){
            		var appJson={};
            		appJson.title="彩宝库存";
           			appJson.function_menu="goods_search";
           			appJson.goods_type="4";
           			YiYi_APP.showExistingPage(JSON.stringify(appJson));
            	}else{
            		location.href = link_url;
            	}
           });
            
            //点击证书号
            $(".cert-href").on("click", function (ev) {
                self.showCert($(this));
            });
            //关闭证书
            $(".close-cert-box-btn").on("click", function (ev) {
                $(".cert-bg-box").hide();
            });
            //继续购买
            $(".go-dias").on("click", function (ev) {
                self.goCart($(this));
            });
            //点击看详情
            $("#cart").on("click",".product-href", function (ev) {
            	var _id =  $(this).attr("lang");
            	var link_url="/Customer/GemDetails/?ID="+_id+"&team=0";
            	if(APP){
            		var appJson={};
           			appJson.title=_("彩宝详情");
           			appJson.url=app_url+link_url;	
           			YiYi_APP.showNewPage(JSON.stringify(appJson));
            	}else{
            		location.href = link_url;
            	}
            });
           	//点击全选
			$("#checkbox_check_all").on("click",function(){
				$(this).toggleClass("selected")
				if($(this).hasClass("selected")){
					$(".check_list_box").children("span").addClass("selected");
					$(".check_list_box span.selected").each(function (i, item) {
						var pre = parseFloat($(item).closest("figure").find(".first").text());//当前点击行的每卡
    					var totalprice = parseFloat($(item).closest("figure").find(".totalprice").text());
    					var totalpriceUSD = parseFloat($(item).closest("figure").find(".totalpriceUSD").text());
						self.countCheck(1,pre,totalprice,totalpriceUSD);
					});		
				}else{
					$(".check_list_box").children("span").removeClass("selected");
					self.countCheck(0,0,0,0);//取消
				}
			});
			//列表的勾选框
			$("#cart").on("click",".check_list_box",function(){
				$(this).children("span").toggleClass("selected");
				var pre = parseFloat($(this).closest("figure").find(".first").text());//当前点击行的每卡
				var totalprice = parseFloat($(this).closest("figure").find(".totalprice").text());
				var totalpriceUSD = parseFloat($(this).closest("figure").find(".totalpriceUSD").text());
				//判断是否全选
				var length=$("#cart .check_list_box span.checkbox").length;
				var checkLength=$("#cart .check_list_box span.selected").length;
				if(length==checkLength){
					$("#checkbox_check_all").addClass("selected");
				}else{
					$("#checkbox_check_all").removeClass("selected");
				}				
				if($(this).children("span").hasClass("selected")){
					self.countCheck(1,pre,totalprice,totalpriceUSD);//选中
				}else{
					self.countCheck(2,pre,totalprice,totalpriceUSD);//取消
				}
				
			});
			//立即购买
			$("#add_to_order").on("click",function(){
				var cartlistCb = $("#cart .check_list_box span.selected");//tbody中checked的
                if (cartlistCb.length == 0) {
                	myApp.alert(_("请选择!"));
                } else {
                	var orderJson={};
                	orderJson.orderID = [];
                	orderJson.type="gems";
                	orderJson.form="cart";
		            for (var i = 0; i < cartlistCb.length; i++) {
		               orderJson.orderID.push(cartlistCb[i].lang);
		            }		           
		            if(APP){
		            	var appJson={};
		            	appJson.title=_("确认下单");
		            	appJson.url=app_url+"/Customer/SubmitDiaOrder?type=4&cart=4";
		            	appJson.content=JSON.stringify(orderJson);
		            	YiYi_APP.submitOrder(JSON.stringify(appJson))
		            }else{
		            	var action="/Customer/SubmitDiaOrder?type=4&cart=4";
					  	form = $("<form method='post' id='params_form' action='"+action+"'>"+
					   	"<input type='text' value='"+JSON.stringify(orderJson)+"' name='params'></form>")
						$("#form_box").html(form);
						$("#params_form").submit();
		            }
                }
			});
			
        },


        //绑定数据
        bindingCart: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if (_result.msgcode == false || _result["msginfo"].rows.length==0) {//获取购物车失败
                $(".null-cart-tip").show();//显示空购物车提示
                $("#cart").hide();//隐藏购物车列表，主要是隐藏列表的边框线

            } else {  //获取购物车成功
                $("#cart").show();//显示购物车内容
                _result = _result["msginfo"].rows;//object;//object  
                 $("#totalCart").html(_result.length);
                var figures = "";//多行数据
                for (var i = 0; i < _result.length ; i++) {//_result.length
                    var figcaption = "";//多列
                    var figure = "";//单行
                    //绑定数据
                    figcaption += "<figcaption class='product-parameter' lang='" + _result[i].ID + "'>"+
                    "<div class='imgList'>"+ShowImgOne(_result[i])+"</div>"+
                    "<h3><b class='list-num' style='display:none'>" + (i + 1) + "</b>" +
                    	"<b class='shape'>" +  GetText("gems",_result[i].Category,_result[i].Shape,"Shape") + "</b>" +
                    	"<b class='size'>" + _result[i].Measurement + "</b><b class='color'>" +GetText("gems",_result[i].Category, _result[i].Color,"Color") + "</b>" +
                    	"<b class='category'>" +GetCategory("gems",_result[i].Category) +"</b><b class='weight'>" + _result[i].Weight + "</b>"+
                   	 	"<b class='place'>" + GetText("gems",_result[i].Category,_result[i].Place,"Place") + "</b>"+
                   	"</h3>" +
                   	"<div class='product-price CurrentRMB'>"+
                   		 	"<span>"+_("每卡")+"￥：<b class='first'>" + formatRMBPrice(_result[i].Price) + "</b></span>" +
                   			"<span>"+_("总价")+"￥：<b class='totalprice'>" + formatRMBPrice(_result[i].Price * _result[i].Weight) + "</b></span>"+
                   		"</div>"+
                   		"<div class='product-price CurrentUSD'>"+
                   		 	"<span>"+_("每卡")+"$：<b class='firstUSD'>" + formatUSDPrice(_result[i].Price/RATE) + "</b></span>" +
                   			"<span>"+_("总价")+"$：<b class='totalpriceUSD'>" + formatUSDPrice(_result[i].Price * _result[i].Weight/RATE) + "</b></span>"+
                   		"</div>"+
                    "</div></figcaption>";
                    figure += "<figure class='product-list' data-time='" + DateTimeFormat(_result[i].UpdateTime) + "'>" +
                     	"<div class='check_list_box'><span class='checkbox' name='checkbox' lang='" + _result[i].ID + "'></span></div>"+
                       "<a href='javacript:void(0)' class='product-href' lang='" + _result[i].ID + "' data-sn='" + _result[i].OriginSN + "'>" + figcaption + "</a></figure>";

                    figures += figure;//将单行加到多行
                }

                $("#cart").html(figures);//加入到id为inventory的figures中
                currentShow();  //币种设置

            }

        },

        //加载购物车
        loadCart: function () {
            var self = this;
            myApp.showIndicator();//显示加载中
            var result = {};
            result.CustomerID = CustomerID;//客户ID
            result.PageSize = 1;
            result.PageIndex = 1;
            result.type = 4;
            $.ajax({
                url: "/Customer/GetCartInfos",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(result),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    self.bindingCart(result);//绑定购物车
                    self.clearTotal();//清空选中统计
                    myApp.hideIndicator();//隐藏加载中

                }
            });
        },
        
     
        //移除购物车
        removeCart: function () {
            var self = this;
            //获取ID值
            var result = {};
            result.CustomerID = CustomerID;//客户ID
			var cartlistCb = $("#cart .check_list_box span.selected");//获取选中的行
			var _IDs = "";
            for (var i = 0; i < cartlistCb.length; i++) {
                if (i == 0)
                    _IDs += cartlistCb[i].lang;
                else
                    _IDs += "," + cartlistCb[i].lang;
            }
            result.GemID = _IDs;
            $.ajax({
                url: "/Customer/RemoveGemsCart",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(result),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象

                    if (_result['msgcode'] == false) {
                        toast(_result['msginfo']);
                    } else {
                        $("#removeTip").hide();
                        toast(_result['msginfo']);
                        setTimeout(function () {
                            $(".detail-box-bg").hide();
                        }, 1000);
                        self.loadCart();
                        //启用滚动条
                        $("body").css({
                            "overflow": "auto",
                            'position': 'static',
                            'top': 'auto'
                        });
                        $("body").scrollTop(scrollToph);

                    }
                }
            });
        },

        
        countCheck:function(type,pre,totalPrice,totalPriceUSD){			
			var price=parseFloat($("#check-total-price").text());
			var priceUSD=parseFloat($("#check-total-priceUSD").text());
			var pre_price=parseFloat($("#check-m-rmb").text());
			var _num = $(".check_list_box span.selected").length;;	
			if(type==1){//加
				price+=totalPrice
				priceUSD+=totalPriceUSD
				pre_price+=pre
			}
			if(type==2){//减
				price-=totalPrice
				priceUSD-=totalPriceUSD
				pre_price-=pre
			}
			if(type==0){
				_num=0;
				price=0;
				priceUSD=0;
				pre_price=0;
			}
			
			$("#check-num").text(_num);
			$("#check-m-rmb").text(formatRMBPrice(pre_price));
			$("#check-total-price").text(formatRMBPrice(price));
			$("#check-total-priceUSD").text(formatUSDPrice(priceUSD));
		},
        //清空统计栏
        clearTotal: function () {
            $("#check-num").html(0);
            $("#check-m-rmb").html(0);
            $("#check-total-price").html(0);
            $("#check-total-priceUSD").html(0);
        },
    };
    cart.init();
})();
